import json
import time
from pathlib import Path
from typing import Dict, Any, List, Optional, Union
from .logger import test_logger
from .report_sender.sender_factory import ReportSenderFactory

class ReportManager:
    """报告管理器"""
    
    def __init__(self, config_path: str = "report_config.json"):
        """初始化报告管理器
        
        Args:
            config_path: 配置文件路径
        """
        self.config_path = Path(__file__).parent.parent / config_path
        self.logger = test_logger.get_logger(self.__class__.__name__)
        self.config = self._load_config()
        
    def _load_config(self) -> Dict[str, Any]:
        """加载配置文件
        
        Returns:
            配置信息
        """
        try:
            if self.config_path.exists():
                with open(self.config_path, 'r', encoding='utf-8') as f:
                    return json.load(f)
            return {}
        except Exception as e:
            self.logger.error(f"Failed to load config: {str(e)}")
            return {}
            
    def send_report(self, report_path: Path, title: str, content: Optional[str] = None,
                   report_format: str = 'html', test_results: Optional[List[Dict[str, Any]]] = None):
        """发送测试报告
        
        Args:
            report_path: 报告文件路径
            title: 报告标题
            content: 报告内容（可选）
            report_format: 报告格式（html/markdown/text）
            test_results: 测试结果列表（可选）
        """
        if not self.config:
            self.logger.warning("No report configuration found")
            return
            
        # 生成报告内容
        if test_results and not content:
            content = self.generate_report_content(test_results, report_format)
            
        # 发送报告
        for sender_type, sender_config in self.config.items():
            try:
                sender = ReportSenderFactory.get_sender(sender_type, sender_config)
                if sender.send_report(report_path, title, content):
                    self.logger.info(f"Successfully sent report via {sender_type}")
                else:
                    self.logger.error(f"Failed to send report via {sender_type}")
            except Exception as e:
                self.logger.error(f"Failed to send report via {sender_type}: {str(e)}")
                
    def generate_report_content(self, test_results: List[Dict[str, Any]], 
                              format: str = 'html') -> str:
        """生成报告内容
        
        Args:
            test_results: 测试结果列表
            format: 报告格式（html/markdown/text）
            
        Returns:
            报告内容
        """
        # 计算测试统计信息
        total = len(test_results)
        passed = sum(1 for r in test_results if r.get('status') == 'passed')
        failed = sum(1 for r in test_results if r.get('status') == 'failed')
        skipped = sum(1 for r in test_results if r.get('status') == 'skipped')
        duration = sum(r.get('duration', 0) for r in test_results)
        
        # 生成报告内容
        if format == 'html':
            return self._generate_html_report(test_results, total, passed, failed, skipped, duration)
        elif format == 'markdown':
            return self._generate_markdown_report(test_results, total, passed, failed, skipped, duration)
        else:
            return self._generate_text_report(test_results, total, passed, failed, skipped, duration)
            
    def _generate_html_report(self, test_results: List[Dict[str, Any]], 
                            total: int, passed: int, failed: int, skipped: int,
                            duration: float) -> str:
        """生成HTML格式报告
        
        Args:
            test_results: 测试结果列表
            total: 总用例数
            passed: 通过数
            failed: 失败数
            skipped: 跳过数
            duration: 总耗时
            
        Returns:
            HTML格式报告内容
        """
        content = f"""
        <html>
        <head>
            <style>
                body {{ font-family: Arial, sans-serif; margin: 20px; }}
                table {{ border-collapse: collapse; width: 100%; }}
                th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
                th {{ background-color: #f2f2f2; }}
                .passed {{ color: green; }}
                .failed {{ color: red; }}
                .skipped {{ color: orange; }}
                .summary {{ margin-bottom: 20px; }}
            </style>
        </head>
        <body>
            <h2>测试报告</h2>
            <div class="summary">
                <p>总用例数: {total}</p>
                <p>通过: <span class="passed">{passed}</span></p>
                <p>失败: <span class="failed">{failed}</span></p>
                <p>跳过: <span class="skipped">{skipped}</span></p>
                <p>通过率: {passed/total*100:.2f}%</p>
                <p>总耗时: {duration:.2f}秒</p>
            </div>
            
            <h3>测试详情</h3>
            <table>
                <tr>
                    <th>用例名称</th>
                    <th>状态</th>
                    <th>耗时</th>
                    <th>错误信息</th>
                </tr>
        """
        
        for result in test_results:
            status_class = result.get('status', '').lower()
            content += f"""
                <tr>
                    <td>{result.get('name', '')}</td>
                    <td class="{status_class}">{result.get('status', '')}</td>
                    <td>{result.get('duration', 0):.2f}s</td>
                    <td>{result.get('error', '')}</td>
                </tr>
            """
            
        content += """
            </table>
        </body>
        </html>
        """
        return content
        
    def _generate_markdown_report(self, test_results: List[Dict[str, Any]], 
                                total: int, passed: int, failed: int, skipped: int,
                                duration: float) -> str:
        """生成Markdown格式报告
        
        Args:
            test_results: 测试结果列表
            total: 总用例数
            passed: 通过数
            failed: 失败数
            skipped: 跳过数
            duration: 总耗时
            
        Returns:
            Markdown格式报告内容
        """
        content = f"""# 测试报告

## 测试统计
- 总用例数: {total}
- 通过: {passed}
- 失败: {failed}
- 跳过: {skipped}
- 通过率: {passed/total*100:.2f}%
- 总耗时: {duration:.2f}秒

## 测试详情
| 用例名称 | 状态 | 耗时 | 错误信息 |
|---------|------|------|----------|
"""
        
        for result in test_results:
            content += f"| {result.get('name', '')} | {result.get('status', '')} | {result.get('duration', 0):.2f}s | {result.get('error', '')} |\n"
            
        return content
        
    def _generate_text_report(self, test_results: List[Dict[str, Any]], 
                            total: int, passed: int, failed: int, skipped: int,
                            duration: float) -> str:
        """生成文本格式报告
        
        Args:
            test_results: 测试结果列表
            total: 总用例数
            passed: 通过数
            failed: 失败数
            skipped: 跳过数
            duration: 总耗时
            
        Returns:
            文本格式报告内容
        """
        content = f"""测试报告

测试统计:
- 总用例数: {total}
- 通过: {passed}
- 失败: {failed}
- 跳过: {skipped}
- 通过率: {passed/total*100:.2f}%
- 总耗时: {duration:.2f}秒

测试详情:
"""
        
        for result in test_results:
            content += f"""
用例名称: {result.get('name', '')}
状态: {result.get('status', '')}
耗时: {result.get('duration', 0):.2f}秒
错误信息: {result.get('error', '')}
-------------------
"""
            
        return content 